﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppMVVM.WCFWebRoleService;
using System.Windows.Controls;
using System.Xml.Linq;

namespace AppMVVM.Models
{
    public class Source : INotifyPropertyChanged
    {
        private UserSubscriptionInformation _subscription;
        private Lazy<IEnumerable<Article>> _articles;

        public Source(UserSubscriptionInformation subscription)
        {
            _articles = new Lazy<IEnumerable<Article>>(() => LoadArticles());
            _subscription = subscription;
        }

        public UserSubscriptionInformation Subscription
        {
            get { return _subscription; }
        }

        public IEnumerable<Article> Articles
        {
            get { return LoadArticles(); }
        }

        private IEnumerable<Article> LoadArticles()
        {
            var reader = XDocument.Load(Subscription.Url);
            var articles = from item in reader.Descendants("item")
                           select new Article(item);

            return articles;
        }

        public string Name
        {
            get
            {
                if (_subscription != null)
                    return _subscription.Title ?? _subscription.Url;
                return null;
            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
